//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from 'react';
import type { NodeProps } from "reactflow";
import { NodeData } from '../types';
import LocalNodeWrap from '../LocalNodeWrap';
import { Button, Space, Table } from 'antd';
import { ExportOutlined, ReloadOutlined } from '@ant-design/icons';
import type { GitLabTodo } from "@/api/gitlab/todo";
import { list_todo } from "@/api/gitlab/todo";
import type { GitLabUser } from "@/api/gitlab/common";
import { get_self_info } from "@/api/gitlab/user";
import { get_type_name, type UserDataSourceInfo, type GitSourceInfo, get_source } from '@/api/user_dataview';
import { open as shell_open } from '@tauri-apps/api/shell';
import type { ColumnsType } from 'antd/lib/table';
import moment from 'moment';


const GitLabTodoListNode = (props: NodeProps<NodeData>) => {
    const [userInfo, setUserInfo] = useState<GitLabUser | null>(null);
    const [todoList, setTodoList] = useState<GitLabTodo[]>([]);
    const [dataSource, setDataSource] = useState<UserDataSourceInfo | undefined>(undefined);

    const loadDataSource = async () => {
        const res = await get_source(props.data.dataSourceId ?? "");
        setDataSource(res);
    };

    const loadUserInfo = async () => {
        if (dataSource == undefined) {
            return;
        }
        const sourceInfo = JSON.parse(dataSource.source_info) as GitSourceInfo;
        const url = new URL(sourceInfo.baseUrl ?? "");
        const baseUrl = `${url.protocol}//${url.host}`;
        const res = await get_self_info(baseUrl, sourceInfo.accessToken);
        setUserInfo(res);
    };

    const loadTodoList = async () => {
        if (dataSource == undefined) {
            return;
        }
        const sourceInfo = JSON.parse(dataSource.source_info) as GitSourceInfo;
        const url = new URL(sourceInfo.baseUrl ?? "");
        const baseUrl = `${url.protocol}//${url.host}`;
        const res = await list_todo(baseUrl, sourceInfo.accessToken);
        setTodoList(res);
    };


    const getSourceTypeName = () => {
        if (dataSource == undefined) {
            return "";
        }
        return get_type_name(dataSource.source_type);
    };

    const columns: ColumnsType<GitLabTodo> = [
        {
            title: "标题",
            render: (_, row: GitLabTodo) => (
                <a href={row.target.web_url} target="_blank" rel="noreferrer">{row.target?.title ?? ""}&nbsp;<ExportOutlined /></a>
            ),
        },
        {
            title: "创建时间",
            width: 120,
            render: (_, row: GitLabTodo) => moment(row.created_at).format("YYYY-MM-DD HH:mm"),
        },
        {
            title: "更新时间",
            width: 120,
            render: (_, row: GitLabTodo) => moment(row.updated_at).format("YYYY-MM-DD HH:mm"),
        },
    ];


    useEffect(() => {
        loadDataSource();
    }, []);

    useEffect(() => {
        if (dataSource != undefined) {
            loadUserInfo();
            loadTodoList();
        }
    }, [dataSource]);

    return (
        <LocalNodeWrap title={
            <Space>
                <span>{getSourceTypeName()}</span>
                <span>待办事项</span>
                {userInfo != null && (
                    <a onClick={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        shell_open(userInfo.web_url);
                    }}>{userInfo.name}</a>
                )}
            </Space>
        } nodeData={props} extraButtonList={[
            <Button type="text" icon={<ReloadOutlined />} onClick={e => {
                e.stopPropagation();
                e.preventDefault();
                loadTodoList();
            }} title='刷新' />
        ]} canChangeBgColor={false}>
            <Table rowKey="id" dataSource={todoList} columns={columns} pagination={false} scroll={{ y: props.data.height - 100 }} className="nodrag nopan nowheel"
            />
        </LocalNodeWrap>
    );
};

export default GitLabTodoListNode;